package com.example.biji;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    private NoteDatabase dbHelper;
    private static  String code="0000";
    private final Context context = this;/*在很多构造器中需要*/
    FloatingActionButton btn;
    private ListView lv;
    private ImageView codeset;

    private NoteAdapter adapter;
    private final List<Note> noteList = new ArrayList<>();
    private Toolbar myToolbar;


    //弹出菜单
    private PopupWindow popupWindow;
    private PopupWindow popupCover;
    private ViewGroup customView;
    private RelativeLayout main;
    private ViewGroup coverView;
    private LayoutInflater layoutInflater;
    private WindowManager wm;
    private DisplayMetrics metrics;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = findViewById(R.id.fab);
        lv = findViewById(R.id.lv);
        adapter = new NoteAdapter(getApplicationContext(), noteList);
        refreshListView();/*刷新视图*/
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);
        myToolbar = findViewById(R.id.myToolbar);
        initPopUpView();
        setSupportActionBar(myToolbar);
        try {
            getSupportActionBar().setHomeButtonEnabled(true);
        } catch(Exception e) {
            throw new RuntimeException();
        }
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        myToolbar.setNavigationIcon(R.drawable.ic_baseline_menu_24);
        myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopUpView();
            }
        });



        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, EditActivity.class);/*跳转到MainActivity页面*/
                intent.putExtra("mode", 4);/*这是新建记录，mode为4,区分修改记录*/
                startActivityForResult(intent, 0);/*开始intent相关的Edit活动*/
            }
        });
        getPermissionCamera(this);
    }

    private void dialog(){
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.dialog_code, null);
        final EditText old_code = (EditText) textEntryView.findViewById(R.id.old_code);
        final EditText new_code = (EditText)textEntryView.findViewById(R.id.new_code);
        AlertDialog.Builder ad1 = new AlertDialog.Builder(MainActivity.this);
        ad1.setTitle("更改密码，初始密码是0000哦");
        ad1.setIcon(android.R.drawable.ic_dialog_info);
        ad1.setView(textEntryView);
        ad1.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(old_code.getText().toString().equals(code)){
                    code=new_code.getText().toString();
                    success();
                }
                else{
                    fail();
                }
            }
        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();
    }

    //渲染
    private void initPopUpView(){
        layoutInflater=(LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        customView=(ViewGroup)layoutInflater.inflate(R.layout.setting_layout,null);
        coverView=(ViewGroup)layoutInflater.inflate(R.layout.setting_cover,null);
        main=findViewById(R.id.main_layout);
        wm=getWindowManager();
        metrics=new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
    }

    public void showPopUpView(){
        int width=metrics.widthPixels;
        int height=metrics.heightPixels;

        popupCover =new PopupWindow(coverView,width,height,false);
        popupWindow=new PopupWindow(customView,(int)(width*0.7),height,true );
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

        //在主界面加载成功后，显示弹出
        findViewById(R.id.main_layout).post((new Runnable() {
            @Override
            public void run() {
                popupCover.showAtLocation(main, Gravity.NO_GRAVITY,0,0);
                popupWindow.showAtLocation(main,Gravity.NO_GRAVITY,0,0);
                codeset = customView.findViewById(R.id.setting_img);

                codeset.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog();
                    }
                });

                coverView.setOnTouchListener(new View.OnTouchListener(){
                    @Override
                    public boolean onTouch(View v, MotionEvent event){
                        popupWindow.dismiss();
                        return true;
                    }
                });

                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        popupCover.dismiss();
                    }
                });

            }

        }));

    }

    //接收startActivityForResult的结果，保存在data中
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        int returnMode;
        long note_id;
        Bundle bd;
        try{
            bd = data.getExtras();
        } catch(Exception e) {
            throw new RuntimeException();
        }
        returnMode = bd.getInt("mode",-1);/*mode,默认是-1，代表什么都不用做*/
        note_id = bd.getLong("id", 0);/*默认值的意思就是，没找到就是默认值*/

        /*根据返回mode判断，-2代表什么都不做，0代建表新,1或者-1代表修改*/
        if(returnMode == 1 || returnMode == -1) {
            String content = bd.getString("content");
            String time = bd.getString("time");
            int tag = bd.getInt("tag", 1);
            int flag = bd.getInt("flag");
            String path = bd.getString("path");
            String location = bd.getString("location","location");

            Note newNote = new Note(content, time, tag, path, flag, location);
            newNote.setId(note_id);
            CRUD op = new CRUD(context);
            op.open();
            op.updateNote(newNote);  /*修改表中记录*/
            op.close();
        } else if (returnMode == 0) {
            String content = bd.getString("content");
            String time = bd.getString("time");
            int tag = bd.getInt("tag", 1);
            String path = bd.getString("path");/*没有图片，接收到的是"null"*/
            int flag = bd.getInt("flag");
            String location = bd.getString("location");

            Note newNote = new Note(content, time, tag, path, flag, location);
            CRUD op = new CRUD(context);
            op.open();
            op.addNote(newNote);     /*添加到表中*/
            op.close();
        }else if(returnMode==2){
            Note curNote=new Note();
            curNote.setId(note_id);
            CRUD op=new CRUD(context);
            op.open();
            op.removeNote(curNote);
            op.close();
        }
        refreshListView();
        super.onActivityResult(requestCode, resultCode, data);/*调用基类的方法*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case R.id.menu_clear:
                final EditText et = new EditText(this);
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("要删除全部记录要密码哦，你要删吗,赶紧输入我们的暗号")
                        .setIcon(android.R.drawable.sym_def_app_icon)
                        .setView(et)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if(et.getText().toString().equals(code)){
                                    dbHelper =new NoteDatabase(context);
                                    SQLiteDatabase db =dbHelper.getWritableDatabase();
                                    db.delete(NoteDatabase.TABLE_NAME,null,null);
                                    //db.execSQL("update sqlie_sequence set seq=0 where name='notes'");//使序列归零，而不是继续自增
                                    refreshListView();
                                }
                                else{
                                    fail();
                                }
                            }
                        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                }).create().show();
                break;


        }


        return super.onOptionsItemSelected(item);
    }



    public void success(){
        new AlertDialog.Builder(MainActivity.this)
                .setMessage("密码修改成功！")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();
    }

    public void fail(){
        new AlertDialog.Builder(MainActivity.this)
                .setMessage("密码不对哦！")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();
    }




    /*刷新数据*/
    public void refreshListView(){
        CRUD op = new CRUD(context);
        op.open();
        // set adapter
        if (noteList.size() > 0) {
            noteList.clear();/*有记录的话，清除全部*/
        }
        noteList.addAll(op.getAllNotes());  /*在添加现在的所有记录*/
        op.close();
        adapter.notifyDataSetChanged();
        /*notifyDataSetChanged方法通过一个外部的方法控制如果适配器的内容改变时需要强制调用getView来刷新每个Item的内容。*/
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {   /*第几个记录被点击，对应id，然后对应该记录*/
            case R.id.lv:
                Note curNote = (Note) parent.getItemAtPosition((position));
                if(curNote.getFlag()==0){
                    Intent intent = new Intent(MainActivity.this, EditActivity.class);
                    intent.putExtra("content", curNote.getContent());
                    intent.putExtra("id", curNote.getId());
                    intent.putExtra("time", curNote.getTime());
                    intent.putExtra("mode", 3);            /*代表已经点击过了,与EditActivity接受对应*/
                    intent.putExtra("tag", curNote.getTag());
                    intent.putExtra("path", curNote.getPath());
                    intent.putExtra("flag", 0);
                    intent.putExtra("location",curNote.getLocation());
                    startActivityForResult(intent, 1);     /*开始跳转*/
                }
                else if(curNote.getFlag() == 1) {
                    final EditText et = new EditText(this);
                    new AlertDialog.Builder(MainActivity.this)
                            .setMessage("这是个私密记录哦，你要查看吗,赶紧输入我们的暗号")
                            .setIcon(android.R.drawable.sym_def_app_icon)
                            .setView(et)
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if(et.getText().toString().equals(code)){
                                        Intent intent = new Intent(MainActivity.this, EditActivity.class);
                                        intent.putExtra("content", curNote.getContent());
                                        intent.putExtra("id", curNote.getId());
                                        intent.putExtra("time", curNote.getTime());
                                        intent.putExtra("mode", 3);            /*代表已经点击过了,与EditActivity接受对应*/
                                        intent.putExtra("tag", curNote.getTag());
                                        intent.putExtra("path", curNote.getPath());
                                        intent.putExtra("flag",1);
                                        intent.putExtra("location",curNote.getLocation());
                                        startActivityForResult(intent, 1);     /*开始跳转*/
                                    }
                                    else{
                                        fail();
                                    }
                                }
                            }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();
                        }
                    }).create().show();
                }
                break;
        }
    }

    /*获得相机，存储权限*/
    public static boolean getPermissionCamera(Activity activity) {
        int cameraPermissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
        int readPermissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
        int writePermissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int readPhoneStatus = ContextCompat.checkSelfPermission(activity,Manifest.permission.READ_PHONE_STATE);
        int writeExternal = ContextCompat.checkSelfPermission(activity,Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int accessFindLocation = ContextCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_FINE_LOCATION);
        if (cameraPermissionCheck != PackageManager.PERMISSION_GRANTED
                || readPermissionCheck != PackageManager.PERMISSION_GRANTED
                || writePermissionCheck != PackageManager.PERMISSION_GRANTED
                ||readPhoneStatus != PackageManager.PERMISSION_GRANTED
                ||writeExternal != PackageManager.PERMISSION_GRANTED
                ||accessFindLocation != PackageManager.PERMISSION_GRANTED) {
            String[] permissions = new String[]{Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };
            ActivityCompat.requestPermissions(
                    activity,
                    permissions,
                    0);
            return false;
        } else {
            return true;
        }
    }
}

